<?php
namespace Zxf5115\Laravel\Keyword\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Zxf5115\Laravel\Keyword\Logics\KeywordLogic;
use Zxf5115\Laravel\Kernel\Traits\ValidatorTrait;
use Zxf5115\Laravel\Kernel\Controllers\Api\ApiController;

/**
 * @author zhangxiaofei [<1326336909@qq.com>]
 * @dateTime 2025-10-08
 *
 * 关键字控制器类
 */
class KeywordController extends ApiController
{
  use ValidatorTrait;

  /**
   * 排序规则
   */
  protected array $sortRules = [
    ['key' => 'total', 'value' => 'desc'],
    ['key' => 'id', 'value' => 'desc'],
    ['key' => 'create_time', 'value' => 'desc'],
  ];

  /**
   * 记录关键字信息
   *
   * @param Request $request 用户请求参数
   * @param KeywordLogic $logic 关键字逻辑对象
   * @return JsonResponse 响应数据
   */
  public function record(Request $request, KeywordLogic $logic) : JsonResponse
  {
    try
    {
      $messages = [
        'title.required' => '请您输入搜索关键字',
      ];

      $rules = [
        'title' => 'required',
      ];

      // 验证用户数据内容是否正确
      $validation = $this->validation($request, $messages, $rules);

      if(!$validation['status'])
      {
        return error($validation['message']);
      }

      // 关键字记录处理
      $logic->record($request, $this->modelClass);

      return success(__('kernel.handle_success'));
    }
    catch(\Exception $e)
    {
      // 记录异常信息
      record($e);

      return error(__('kernel.handle_failure'));
    }
  }
}
